package com.cheng.web.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.cheng.bos.actionUtils.ActionUtils;
import com.cheng.bos.foreUtils.MailUtils;
import com.cheng.bos.foreUtils.SmsUtils;
import com.cheng.domain.Customer;
import com.opensymphony.xwork2.ActionContext;

@Controller
@Scope("prototype")
@Namespace("/customer")
@ParentPackage("json-default")
public class CustomerAction extends ActionUtils<Customer> {
	
	//注入消息队列将短信和邮件交由消息队列发送
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	@Autowired
	private RedisTemplate<String, String> redistemlate;
	//属性驱动获取验证码
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	
	@Action(value="customer_regist",results={@Result(name="success",type="redirect",location="../signup-success.html"),
			@Result(name="input",type="redirect",location="signup.html")})
	public String registeCustomer(){
		String sendcode = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if (sendcode!= null && sendcode.equals(checkcode)) {
			WebClient.create("http://localhost:9002/crm_management/service/customerService").path("/registecustomer").post(model);
			
			String activeUrl = "http://localhost:9003/bos_fore/customer";
			//获取32位随机数作为验证码
			String activecode = RandomStringUtils.randomNumeric(32);
			//将验证码存入redis中
			redistemlate.opsForValue().set(model.getTelephone(), activecode,24,TimeUnit.HOURS);
			
			String content = "<h3>请点击下方地址激活:<br/><a href=" + activeUrl+ "/active?telephone="+model.getTelephone()+"&activecode=" + activecode + ">点击激活邮箱</a></h3>";
			
			jmsTemplate.send("bos_email", new MessageCreator() {
				
				@Override
				public Message createMessage(Session session) throws JMSException {
					MapMessage mapMessage = session.createMapMessage();
					mapMessage.setString("address", model.getEmail());
					mapMessage.setString("content", content);
					return mapMessage;
				}
			});
			
			
			return SUCCESS;
		}
		System.out.println("验证码错误");
		return INPUT;
	}
	
	@Action(value="customer_sendSms",results={@Result(name="error",type="json")})
	public String sendMesg(){
		Customer customer = WebClient.create("http://localhost:9002/crm_management/service/customerService").path("/getcustomerbytel/"+model.getTelephone()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
		if (customer != null) {
			String mesg = "手机号码已被使用!";
			ActionContext.getContext().getValueStack().push(mesg);
			return ERROR;
		}
		String sendcode = RandomStringUtils.randomNumeric(4);
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), sendcode);
		System.out.println("验证码:"+sendcode);
		String mesg = "您好,您本次的验证码为:"+sendcode;
		
		//调用消息队列模板创建消息
		jmsTemplate.send("bos_telephonecode",new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("mesg", mesg);
				return mapMessage;
			}
		});
		return NONE;
	}
	
	private String activecode;
	
	
	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	@Action(value="active",results={@Result(name="success",type="redirect",location="../login.html")})
	public String activeCustomer(){
		try {
			ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
			System.out.println(model.getTelephone());
			String code = redistemlate.opsForValue().get(model.getTelephone());
			if (activecode != null && activecode.equals(code)) {
				Customer customer = WebClient.create("http://localhost:9002/crm_management/service/customerService").path("/getcustomerbytel/"+model.getTelephone()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
				if (customer == null) {
					ServletActionContext.getResponse().getWriter().println("激活的账号不存在!");
					return NONE;
				}else if(customer.getType() == 1){
					ServletActionContext.getResponse().getWriter().println("账号已经激活!");
					return NONE;
				}else{
					 WebClient.create("http://localhost:9002/crm_management/service/customerService").path("/activecustomer/"+model.getTelephone()).put(null);
					 redistemlate.opsForValue().set(customer.getTelephone(), activecode,0,TimeUnit.SECONDS);
				}
			}
			if(code == null){
				ServletActionContext.getResponse().getWriter().println("验证码过期,请登录重新绑定邮箱!");
				return NONE;
			}
			if(!code.equals(activecode)){
				ServletActionContext.getResponse().getWriter().println("验证码错误,请登录重新绑定邮箱!");
				return NONE;
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	@Action(value="customer_login",results={@Result(type="json")})
	public String login(){
		Customer customer = WebClient.create("http://localhost:9002/crm_management/service/customerService").path("/getcustomerbytel/"+model.getTelephone()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
		Map<String, Object> resault = new HashMap<String, Object>();
		if (customer == null) {
			resault.put("resault", false);
			resault.put("msg", "账户名不存在，请重新输入");
		}else if(!customer.getPassword().equals(model.getPassword())){
			resault.put("resault", false);
			resault.put("msg", "账户名与密码不匹配，请重新输入");
		}else{
			resault.put("resault", true);
		}
		ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
		ActionContext.getContext().getValueStack().push(resault);
		return SUCCESS;
	}
	
}
